package com.heima.search.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.search.dtos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;

@Component
@Slf4j
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient client;


    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = ArticleConstants.ARTICLE_ES_SYNC_QUEUE,durable = "true"),
                    exchange = @Exchange(name = ArticleConstants.ARTICLE_ES_SYNC_TOPIC,type = ExchangeTypes.TOPIC),
                    key = ArticleConstants.ARTICLE_ES_SYNC_ROUTINGKEY
            )
    )
    public void getMessage(String message){
        if (StrUtil.isNotBlank(message)) {
            //数据处理
            SearchArticleVo vo = JSON.parseObject(message, SearchArticleVo.class);

            // 创建请求实例
            IndexRequest indexRequest = new IndexRequest("app_info_article");
            indexRequest.id(vo.getId().toString()).source(JSONUtil.toJsonStr(vo), XContentType.JSON);

            //发送请求
            IndexResponse response = null;
            try {
                response = client.index(indexRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("文章发布同步es数据失败");
            }

            //获取响应结果
            String result = response.getResult().toString();
            if (result.equals("UPDATED") || result.equals("CREATED")) {
                log.info("文章发布同步es数据成功");
            }
        }

    }
}
